<?php 
	include('../conn.php');
	// 生成订单号函数
	function build_order_no(){
	    return date('Ymd') . str_pad(mt_rand(1, 99999), 8, '0', STR_PAD_LEFT);
	}

	$total_numbers = build_order_no();
	/*所有商家、发票、购物券、留言，运费险
		order_shop_data :{shopid:{
			invoiceid:'发票id',
			couponid :'购物券id',
			fan_juan_id:'返卷id',
			msg:'给厂商的留言',
			isbuyFreightRisk:'是否购买了运费险0没购买，1购买',
		}}
	 */
	$order_shop_data = $_REQUEST['order_shop_data'];

	/*
		购买数量,id
		order_goods_car_num:{carid:'购买数量'}
	*/
	$order_goods_car_num = $_REQUEST['order_goods_car_num'];

	/*order_invoice_data = {shopid:{type:'0电子发票,2增值发票',data:{type:'1个人,2单位',name:'名称,content:'内容''},data:{invoice_id:'增值发票id'}}}
	*/
	$order_invoice_data = $_REQUEST['order_invoice_data'];

	//收货地址id
	$addressid = $_REQUEST['addressid'];

	//用户id
	$userid = $_REQUEST['userid'];


	//返回数据
	$result_data_array = array();
	
	if(!$order_shop_data){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少店铺信息';
		echo json_encode($result_data_array);
		exit;
	}

	if(!$order_goods_car_num){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少商品信息';
		echo json_encode($result_data_array);
		exit;
	}

	if(!$addressid ){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少收货地址';
		echo json_encode($result_data_array);
		exit;
	}

	if(!$userid){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少用户信息';
		echo json_encode($result_data_array);
		exit;
	}

	$order_shop_data = json_decode($order_shop_data,true);
	if(!$order_shop_data){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '店铺信息格式错误';
		echo json_decode($result_data_array);
		exit;

	}

	$order_goods_car_num = json_decode($order_goods_car_num,true);

	if(!$order_goods_car_num){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '商品信息格式错误';
		echo json_decode($result_data_array);
		exit;

	}

	$order_invoice_data = json_decode($order_invoice_data);
	if(!$order_goods_car_num){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '发票信息格式错误';
		echo json_decode($result_data_array);
		exit;

	}

	// 查找送货地址
	$query = '';
	if ($addressid != '') {
		$query = mysql_query("select * from address where id=".$addressid);
	}else{
		// 默认地址
		$query = mysql_query("select * from address where userid=".$userid." and state = 1");
		// 默认地址 end
	}

	$myaddress = mysql_fetch_assoc($query);

	if(!$myaddress){
		$result_data_array['code'] = -100;
		$result_data_array['msg'] = '没有查询到收货地址';
		echo json_decode($result_data_array);
		exit;
	}

	



	//查询所有购物车商品
	$all_car_goods = array();
	foreach ($order_goods_car_num as $carid => $addnum) {
		$sql = "select car.carid, goods.goodsid,goods.muid,goods.zixilie,goods.shopid,car.price from goods left join car on goods.goodsid = car.goodsid where car.carid = ".$carid." and car.userid = ".$userid." and car.state = 0";
		$query = mysql_query($sql);
		$result = mysql_fetch_assoc($query);


		if(!$result || !$order_shop_data[$result['shopid']]){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '商品信息异常1';
			echo json_encode($result_data_array);
			exit;
		}

		/*所有商家、发票、购物券、留言，运费险
		order_shop_data :{shopid:{
			invoiceid:'发票id',
			couponid :'购物券id',
			fan_juan_id:'返卷id',
			msg:'给厂商的留言',
			isbuyFreightRisk:'是否购买了运费险0没购买，1购买',
		}}
	 */
		$shop_key = $result['shopid']+"";
		if(!$all_car_goods[$shop_key]){
			$all_car_goods[$shop_key] = array();
			$all_car_goods[$shop_key]['goods'] = array();
		}
		$result['addnum'] = $addnum;
		$all_car_goods[$shop_key]['goods'][] = $result;
	}

	//循环计算每个商家的商品
	foreach ($all_car_goods as $shopid => $goodsList) {
		//一个商家的商品总的快递费 
		$total_freightRisk = 0;
		//一个商家的商品总的运费险
		$total_Freight = 0;
		//一个商家所有商品价格
		$total_shop_goods_price = 0;

		//查询每个商家的商品信息
		foreach ($all_car_goods[$shopid]['goods'] as $k => $goods) {
			$addnum = $goods['addnum'];
			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[quyu]."%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
	
			$result0 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[city]."%'  AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result1 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result2 = mysql_fetch_assoc($sql);


			$sql = mysql_query("select * from fare where `area` like '%0%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result3 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[quyu]."%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result4 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[city]."%'  AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result5 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result6 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%0%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result7 = mysql_fetch_assoc($sql);
			
			if ($result0) {
				$where_area = "AND `area` like '%".$myaddress[quyu]."%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result1) {
				$where_area = "AND `area` like '%".$myaddress[city]."%' AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result2) {
				$where_area = "AND `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result3){
				$where_area = "AND `area` like '%0%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result4) {
				$where_area = "AND `area` like '%".$myaddress[quyu]."%' and muid in (select id from fareml where shopid = 0)";
			}elseif ($result5) {
				$where_area = "AND `area` like '%".$myaddress[city]."%' AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid in (select id from fareml where shopid = 0)";
			}elseif ($result6) {
				$where_area = "AND `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid in (select id from fareml where shopid = 0)";
			}else{
				$where_area = "AND `area` like '%0%' and muid in (select id from fareml where shopid = 0)";
			}
			// 运费条件 end
			
			// 计算运费 
				
			$sql = mysql_query("select * from fare  WHERE muid = ".$goods['muid']."  ".$where_area);
			$fare_row  = mysql_fetch_assoc($sql);
			if($fare_row){
				$fare = $fare_row['fare'];
				$addfare = $fare_row['addfare'];
				$begincount = $fare_row['begincount'];
				$distance_count = $fare_row['distance_count'];

				//加上初始件数运费
				
				$fare+=0;
				$begincount+=0;
				$distance_count+=0;
				$total_freightRisk += $fare;
				//购买的件数大于初始件数
				

				if($addnum > $begincount){
					//计算超过件数
					$distance_num = $addnum - $begincount;
					//计算需要加多少次，向下取整
					$addfare_count = floor($distance_num/$distance_count);

					$total_freightRisk += $addfare_count*$addfare;

				}


			}
				
			// 计算运费 end

			// 计算运费险
			$query = mysql_query("select * from freightrisk");
			$freightRisk = 0;
			while ($row = mysql_fetch_assoc($query)) {
				if ($addnum >= $row[goodsNum]) {
					$freightRisk = $row[freightRisk];
				}
			}
			$total_Freight += $freightRisk;
			
			//计算价格
			$total_shop_goods_price = round($total_shop_goods_price*100  + $goods['price']*100*$goods['addnum'])/100;
		}

		
		$all_car_goods[$shopid]['addnum'] = $addnum;
		//计算商品总价格，紧缺到两位小数
		$all_car_goods[$shopid]['total_price'] = $total_shop_goods_price;
		//快递费
		$all_car_goods[$shopid]['total_freightRisk'] = $total_freightRisk;
		//运费险
		$all_car_goods[$shopid]['total_Freight'] = $total_Freight;
		//生成订单号
		$all_car_goods[$shopid]['numbers'] = build_order_no();
		$all_car_goods[$shopid]['address'] = $myaddress['province'].",".$myaddress['city'].",".$myaddress['quyu'].",".$myaddress['address'].",".$myaddress['name'].",".$myaddress['tel'];
	}
	//开始生成订单和查询优惠券、返卷、运费险信息,计算全部订单的价格；
	//优惠券id，返卷id，留言等 存在 $order_shop_data
	/*所有商家、发票、购物券、留言，运费险
		order_shop_data :{shopid:{
			invoiceid:'发票id',
			couponid :'购物券id',
			fan_juan_id:'返卷id',
			msg:'给厂商的留言',
			isbuyFreightRisk:'是否购买了运费险0没购买，1购买',
		}}
	 */
	
	//全部订单的总价格
	$order_total_price = 0;
	mysql_query("BEGIN");

	foreach ($all_car_goods as $shopid => $shop_car_goods_info) {
		//查询优惠券信息
		$now_date = date();
		$couponid = $order_shop_data['couponid'];
		$coupon_result ;
		if($couponid != 0){
			$coupon_query = mysql_query('select coupon.price from coupon left join mycoupon on coupon.couponid = mycoupon.couponid where coupon.couponid = '.$couponid.' and coupon.top_price < '.$shop_car_goods_info['total_price'].' and coupon.startdate < "'.$now_date.'" and coupon.enddate > "'.$now_date.'" and mycoupon.is_use = 0');
			$coupon_result = mysql_fetch_assoc($coupon_query);
			if(!$coupon_result){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '优惠券异常';
				echo json_encode($result_data_array);
				exit;
			}
		}
			

		$numbers = $shop_car_goods_info['numbers'];
		$totalprice = $shop_car_goods_info['total_price'];//订单总价
		$state = 0;//订单状态，待付款
		//$userid = $userid;
		$address = $shop_car_goods_info['address'];//收货地址
		//$shopid = $shopid;
		$buyFreightRisk = $order_shop_data[$shopid]['isbuyFreightRisk'];//是否购买运费险0是1否
		$freightRisk_price = $buyFreightRisk == 1 ? $shop_car_goods_info['total_Freight'] : 0;//运费险
		$distribution_fee = $shop_car_goods_info['total_freightRisk'];//运费
		$msg = $order_shop_data[$shopid]['msg'];
		$type = 0;
		$invoiceid = $order_shop_data[$shopid]['invoiceid'];
		$coupon_price = $couponid != 0?$coupon_result['price']:0;
		$xia_dan_datetime = date("Y-m-d H:i:s");//下单时间

/*		$usersFirstId = '2591';
		var_dump($usersFirstId);die;
		if($usersFirstId) {
			$query = mysql_query("SELECT * FROM orders_users_first WHERE id = " . $usersFirstId);
			$usersFirst = mysql_fetch_assoc($query);
			$firstConpon = $usersFirst['amount']*($usersFirst['first_cate_use']*0.01);
			$totalprice -= $firstConpon;
			$usersFirst['lastAmount'] -= $firstConpon;
			$sql = "UPDATE orders_users_first set amount = " . $usersFirst['amount'] . " AND lastAmount = " . $usersFirst['lastAmount'] . " WHERE id = " . $usersFirstId;
			$query = mysql_query($sql);
			var_dump($query);die;
		}*/

		//插入订单
		$sql = "insert into goodsorders(numbers, totalprice, state ,userid, address, shopid, buyFreightRisk, freightRisk_price, distribution_fee, msg, type,invoiceid,coupon_price,total_numbers,xia_dan_datetime)"
			." values('".$numbers."',".$totalprice.",".$state.",".$userid.",'".$address."',".$shopid.",".$buyFreightRisk.",'".$freightRisk_price."',".$distribution_fee.",'".$msg."',".$type.",".$invoiceid.",'".$coupon_price."', '".$total_numbers."','".$xia_dan_datetime."')";
	
		$query = mysql_query($sql);
		$ordersid = mysql_insert_id();
		if(!$ordersid ){
			mysql_query("ROLLBACK");  
			mysql_query("END");
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '提交订单失败1';
			echo json_encode($result_data_array);
			exit;
		}else{
			$goodsid = mysql_fetch_assoc( mysql_query('select goodsid from car where ordersid='.$ordersid) )['goodsid'];
			
		// 计算平台返劵
	    $quanrate=mysql_fetch_assoc( mysql_query('select rate from categroy where xilie=(select xilie from goods where goodsid='.$goodsid.')' ))['rate'];

	    //计算店铺返佣
	    $cateprice=mysql_fetch_assoc( mysql_query('select rates from shop where shopid='.$shopid) )['rates'];
	    $blance_price = $totalprice-$totalprice * ($quanrate+$cateprice)/100 + $distribution_fee;
		mysql_query("UPDATE goodsorders SET blance_price=".$blance_price." where numbers=".$numbers);
		}

		//更新购物车
		
		foreach ($shop_car_goods_info['goods'] as $key => $value) {
			

			$update_car_query = mysql_query("update car set ordersid='".$ordersid."',number=".$value['addnum'].",state=7 where carid = ".$value['carid']." and state=0");
			if(!$update_car_query ){
				mysql_query("ROLLBACK");  
				mysql_query("END");
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '提交订单失败2';
				echo json_encode($result_data_array);
				exit;
			}
		}
	
		
			

		//更新优惠券
		if( $couponid != 0){
			$update_mycoupon_query = mysql_query('update mycoupon set is_use = 1 where id = '.$couponid);
			if(!$update_mycoupon_query ){
				mysql_query("ROLLBACK");  
				mysql_query("END");
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '提交订单失败3';
				echo json_encode($result_data_array);
				exit;
			}
		}
			
		$order_total_price += $distribution_fee;
		$order_total_price += $freightRisk_price;
		$order_total_price += $totalprice;
		$order_total_price -= $coupon_price;
		
		
	}

	$result_data_array['code'] =  200;
	$result_data_array['zongjia'] =  $order_total_price;
	$result_data_array['numbers'] =  $total_numbers;
	$result_data_array['msg'] = '提交订单成功';

	echo json_encode($result_data_array);

	mysql_query("COMMIT"); 
	mysql_query("END"); 
	



	



 ?>